package com.zy.yun.utils;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zy.yun.base.constant.Const;
import com.zy.yun.base.entity.User;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 王彦委
 * @Description: 数据权限过虑
 * @Date: 11:50 2019/11/10
 */
@Component
public class DataFilterUtil<T> {

    @Autowired
    private RedisUtil<User, List> redisUtil;


    public void setDataFilter(HttpServletRequest request, EntityWrapper<T> queryWrapper) {


        String token = request.getHeader("Authorization");
        if (StringUtils.isBlank(token)) {
            return;
        }
        //根据token,查询用户信息
        User userInfo = redisUtil.getMapObject(Const.TOKEN_MAP_NAME, token, User.class);
        if (null == userInfo) {
            return;
        }

        List tableOrganization = redisUtil.getMapObject2(Const.DATABASE_NAME, Const.TABLE_SYS_ROLE_ORGANIZATION, List.class);
        //如果组织表为空，则不使用数据权限过虑
        if (CollectionUtils.isEmpty(tableOrganization)) {
            return;
        }
        //用于存放，拥有的组织id
        ArrayList<Long> organizationIds = new ArrayList<>();
        List roleOrganizationList = redisUtil.getMapObject2(Const.DATABASE_NAME, Const.TABLE_SYS_ROLE_ORGANIZATION, List.class);

        if (CollectionUtils.isEmpty(roleOrganizationList)) {
            return;
        }
        for (Object obj : roleOrganizationList) {
            JSONObject roleOrganization = (JSONObject) obj;
            if (null != userInfo.getRoleId() && userInfo.getRoleId().equals(roleOrganization.getLong("roleId"))) {
                organizationIds.add(roleOrganization.getLong("organizationId"));
            }
        }

        if (CollectionUtils.isNotEmpty(organizationIds)) {
            queryWrapper.in("organizationId", organizationIds);
        }
    }
}
